import G6 from '@antv/g6'
import graphRegisterFn from './graphRegisterFn'
import bindEvent from './graphEvent'
import transformData from './transformData'

export default function ({
  graphRef,
  data,
  defaultZoom,
  minZoom,
  maxZoom,
  mouseZoomable,
  nodeVGap,
  nodeHGap,
  waterMarker,
  showTooltip,
  hideTooltip,
  clickNode,
}) {
  let originWidth = graphRef.value.clientWidth
  let originHeight = graphRef.value.clientHeight

  graphRegisterFn()

  const modesDefault = [
    {
      type: 'collapse-expand',
      onChange(item, collapsed) {
        const data = item.getModel()
        graph.updateItem(item, {
          collapsed,
        })
        data.collapsed = collapsed
        return true
      },
      shouldBegin(e) {
        return e.target.get('name') === 'collapse-icon'
        // return e.item.getModel().type !== 'more-node'
      },
    },
    'drag-canvas',
  ]

  if (mouseZoomable) {
    modesDefault.push('zoom-canvas')
  }

  const graph = new G6.TreeGraph({
    container: graphRef.value,
    width: originWidth,
    height: originHeight,
    animate: false,
    modes: {
      default: modesDefault,
    },
    defaultNode: {
      type: 'default-node',
    },
    defaultEdge: {
      type: 'new-line',
    },
    layout: {
      type: 'mindmap',
      direction: 'H',
      getVGap: () => nodeVGap,
      getHGap: () => nodeHGap,
      getWidth(node) {
        return node._wrapWidth
      },
      getHeight(node) {
        return node._wrapHeight
      },
      getSide(node) {
        return node.data._direction
      },
    },
    minZoom,
    maxZoom,
  })

  // 自定义方法，初始化位移和缩放
  graph.myInit = function () {
    setTimeout(() => {
      const rootNode = graph.findById(data.id)
      graph.zoomTo(defaultZoom)
      graph.focusItem(rootNode, false)
    })
  }

  // 自定义方法，视口变化
  graph.myResize = function () {
    originWidth = graphRef.value.clientWidth
    originHeight = graphRef.value.clientHeight
    graph.changeSize(originWidth, originHeight)
    graph.myInit()
  }

  graph.on('afterrender', function () {
    setTimeout(() => graph.set('animate', true))
    graph.myInit()
  })

  graph.data(transformData(data))

  // 添加水印
  waterMarker?.url &&
    graph.setImageWaterMarker(waterMarker.url, {
      width: waterMarker.width,
      height: waterMarker.height,
      image: {
        width: waterMarker.width,
        height: waterMarker.height,
      },
    })

  graph.render()

  bindEvent({
    graph,
    showTooltip,
    hideTooltip,
    clickNode,
  })

  return graph
}
